package com.yupi.yoj.model.vo;

import cn.hutool.json.JSONUtil;
import com.yupi.yoj.judge.codesandbox.model.JudgeInfo;
import com.yupi.yoj.model.entity.QuestionSubmit;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;
import java.util.Date;

/**
 * 题目提交封装类
 * 专门给前端返回的对象，可以节约网络传输、过滤字段（脱敏）
 * 和 Question 类相比多了 UserVO、QuestionVO 字段
 */
@Data
public class QuestionSubmitVO implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * id
     */
    private Long id;

    /**
     * 编程语言（枚举类存储）
     */
    private String language;

    /**
     * 用户代码
     */
    private String code;

    /**
     * 判题信息（json 对象）
     */
    private JudgeInfo judgeInfo;

    /**
     * 判题状态（0-待判题、1-判题中、2-成功、3-失败） => 枚举类存储
     */
    private Integer status;

    /**
     * 题目 id（逻辑外键）
     */
    private Long questionId;

    /**
     * 创建用户 id（逻辑外键）
     */
    private Long userId;

    /**
     * 创建时间
     */
    private Date createTime;

    /**
     * 更新时间
     */
    private Date updateTime;

    /**
     * 关联查询用户信息
     */
    private UserVO userVO;

    /**
     * 关联对应题目信息
     */
    private QuestionVO questionVO;

    /**
     * 包装类转对象：VO -> Java对象，存到数据库里
     * @param questionSubmitVO
     * @return
     */
    public static QuestionSubmit voToObj(QuestionSubmitVO questionSubmitVO) {
        if (questionSubmitVO == null) {
            return null;
        }
        QuestionSubmit questionSubmit = new QuestionSubmit();
        BeanUtils.copyProperties(questionSubmitVO, questionSubmit);
        // judgeConfig 属性需要另作处理
        // 判题配置字符串转json
        JudgeInfo judgeConfigObj = questionSubmitVO.getJudgeInfo();
        if (judgeConfigObj != null) {
            questionSubmit.setJudgeInfo(JSONUtil.toJsonStr(judgeConfigObj));
        }

        return questionSubmit;
    }

    /**
     * 对象转包装类：Java对象 -> VO，返回给前端
     * @param questionSubmit
     * @return
     */
    public static QuestionSubmitVO objToVo(QuestionSubmit questionSubmit) {
        if (questionSubmit == null) {
            return null;
        }
        QuestionSubmitVO questionSubmitVO = new QuestionSubmitVO();
        BeanUtils.copyProperties(questionSubmit, questionSubmitVO);
        // judgeInfo 属性需要另作处理
        // 判题信息字符串转java对象
        String judgeInfoStr = questionSubmit.getJudgeInfo();
        questionSubmitVO.setJudgeInfo(JSONUtil.toBean(judgeInfoStr, JudgeInfo.class));

        return questionSubmitVO;
    }
}